package com.haiertvbic.tvwa.db;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.content.res.AssetManager;

import com.haiertvbic.tvwa.util.SLog;

/**
 * 初始化数据库
 * @author jing
 *
 */
public class InitAppDataBase {

	/**
	 * 判断数据库文件是否存在
	 * @param context
	 * @return
	 */
	public boolean isDBExist(Context context) {
		boolean bleExistence = false;
		File fInitXml = new File(context.getFilesDir().getParent()+"/databases/database.db");
		if (fInitXml.exists()) {
			bleExistence = true;
		}
		SLog.d("ipg", "database.path == " + context.getFilesDir().getParent()+"/databases/");
		return bleExistence;
	}
	
	/**
	 * 将asserts目录下的database.db复制到程序目录下
	 * @param context
	 * @return
	 */
	public boolean copyDBFile(Context context)
	{
		SLog.d("ipg", "copy db file begin");
		String dbDir = context.getFilesDir().getParent()+"/databases";
		File f = new File(dbDir);
		f.mkdirs();
		AssetManager am = context.getResources().getAssets();
		InputStream in=null;
		FileOutputStream out=null;
		try {
			in=am.open("database.db");
			out = new FileOutputStream(dbDir+"/database.db");
			byte[] buffer = new byte[1024];
			int read=0;
            while ((read = in.read(buffer)) > 0) {
                out.write(buffer, 0, read);
            }
        	out.close();
            in.close();
            return true;
		} catch (IOException e) {
			SLog.d("ipg", "IOException,read config file failed");
			return false;
		} 
	}
	/**
	 * 删除DB文件
	 * @param context
	 * @return
	 */
	public boolean deleteDbFile(Context context){
		SLog.d("ipg", "delete db file begin");
		boolean isDel = false;
		String dbDir = context.getFilesDir().getParent()+"/databases/database.db";
		File f = new File(dbDir);
		if(f.exists()){
			isDel = f.delete();
		}
		return isDel;
	}
	
}
